from django import http
from django.shortcuts import render
from django.utils.timezone import localtime, localdate
from django.views import View

from contents.utils import get_categories
from goods.models import GoodsCategory, SKU, GoodsVisitCount
from django.core.paginator import Paginator

from goods.utils import get_breadcrumb
from utils.response_code import RET


class ListView(View):
    def get(self, request, category_id, page_num):
        # 获取分类信息
        category_data = get_categories()

        # 获取前端传过来的关键字
        # 按照商品创建时间排序
        # http: // www.meiduo.site: 8000 / list / 115 / 1 /?sort = default
        # 按照商品价格由低到高排序
        # http: // www.meiduo.site: 8000 / list / 115 / 1 /?sort = price
        # 按照商品销量由高到低排序
        # http: // www.meiduo.site: 8000 / list / 115 / 1 /?sort = hot
        sort = request.GET.get('sort', 'default')

        if sort == 'default':
            sort_key = '-create_time'
        elif sort == 'price':
            sort_key = 'price'
        elif sort == 'hot':
            sort_key = '-sales'

        # 获取面包屑信息
        # {
        #     "cat1":{
        #         "url":'',
        #         "name":'',
        #     },
        #     "cat2":{
        #         "name":'',
        #     },
        #     "cat3":{
        #         "name":'',
        #     },
        # }

        data = {
            "cat1": {},
            "cat2": {},
            "cat3": {}
        }
        cat3 = GoodsCategory.objects.get(id=category_id)
        data['cat3']['name'] = cat3.name
        data['cat2']['name'] = cat3.parent.name
        data['cat1']['name'] = cat3.parent.parent.name
        data['cat1']['url'] = cat3.parent.parent.goodschannel_set.first().url

        # data = GoodsCategory.objects.get(id=category_id)

        # 获取到所有的商品
        sku_all = SKU.objects.filter(category_id=category_id, is_launched=True).order_by(sort_key)

        # 对商品进行分页
        # 定义每页多少个商品
        per_page = 5
        # 所有页
        pages = Paginator(sku_all, per_page)
        # 指定页
        page = pages.page(page_num)
        # 总页数
        total_page = pages.num_pages
        # 当前页
        current_page = page.number
        # 当前页商品列表
        sku_list = page.object_list

        context = {
            "categories": category_data,
            "breadcrumb": data,
            'sku_list': sku_list,
            'current_page': current_page,
            'total_page': total_page,
            'category_id': category_id,
            'sort': sort,

        }

        return render(request, 'list.html', context=context)


class HotGoodsView(View):
    def get(self, request, category_id):
        #  获取热销产品
        # 1, 初始化数据
        try:
            cat = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            return http.JsonResponse({'code': RET.PARAMERR, 'errmsg': '分类id错误'})

        # 2, 处理业务逻辑
        # skus = SKU.objects.filter(category=cat)
        skus = SKU.objects.filter(category_id=category_id).order_by('-sales')[:2]

        """
        {
            "code":"0",
            "errmsg":"OK",
            "hot_skus":[
                {
                    "id":6,
                    "default_image_url":"http://image.meiduo.site:8888/group1/M00/00/02/CtM3BVrRbI2ARekNAAFZsBqChgk3141998",
                    "name":"Apple iPhone 8 Plus (A1864) 256GB 深空灰色 移动联通电信4G手机",
                    "price":"7988.00"
                },
                {
                    "id":14,
                    "default_image_url":"http://image.meiduo.site:8888/group1/M00/00/02/CtM3BVrRdMSAaDUtAAVslh9vkK04466364",
                    "name":"华为 HUAWEI P10 Plus 6GB+128GB 玫瑰金 移动联通电信4G手机 双卡双待",
                    "price":"3788.00"
                }
            ]
        }
        """
        hot_skus = []

        for sku in skus:
            sku_data = {
                "id": sku.id,
                "default_image_url": sku.default_image_url.url,
                "name": sku.name,
                "price": sku.price
            }
            hot_skus.append(sku_data)

        # 3, 返回响应
        res = {
            'code': RET.OK,
            'errmsg': '成功',
            'hot_skus': hot_skus
        }
        return http.JsonResponse(res)
        pass


class DetailView(View):
    def get(self, request, sku_id):
        # 获取商品详情页
        # 1, 初始化数据
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            pass

        # 2, 处理业务逻辑
        # 获取分类信息
        categories = get_categories()
        # 获取面包屑信息

        breadcrumb = get_breadcrumb(sku.category_id)

        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options



        # 3, 返回响应
        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': goods_specs,

        }
        return render(request, 'detail.html', context=context)
        pass


class DetailVisitView(View):
    def post(self, request, category_id):
        # 统计一下分类的访问量
        # 1, 初始化数据
        try:
            cat = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            return http.JsonResponse({'code': RET.PARAMERR, 'errmsg': '分类id错误'})
        # 2, 处理业务逻辑

        # 2,1 先查看是否有当天的记录

        now_date = localdate()

        try:
            # 2,2 如果有记录, 就累加
            goods_visit_count = GoodsVisitCount.objects.get(date=now_date, category_id=category_id)
            goods_visit_count.count += 1
            goods_visit_count.save()
        except Exception as e:
            # 2,3 如果没有, 就新增一条, 并且count值为1
            goods_visit_count = GoodsVisitCount.objects.create(
                date=now_date,
                category_id=category_id,
                count=1
            )

        # 3, 返回响应
        res = {
            'code': RET.OK,
            'errmsg': '成功'
        }
        return http.JsonResponse(res)
        pass


class GoodsCommentView(View):
    def get(self,request, sku_id):
        # 获取商品的评价信息
        # 1, 初始化数据
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return http.JsonResponse({'code': RET.PARAMERR,'errmsg': '商品信息有误'})

        # 2, 处理业务逻辑
        """
        {
        "code":"0",
        "errmsg":"OK",
        "comment_list":[
            {
                "username":"itcast",
                "comment":"这是一个好手机！",
                "score":4
            }
        ]
    }
        """
        comment_list = []

        order_goods_all = sku.ordergoods_set.all()
        for order_goods in order_goods_all:
            user = order_goods.order.user
            if order_goods.is_anonymous:
                username = user.username[0] + '****' + user.username[-1]
            else:
                username = user.username
            order_goods_data = {
                "username": username,
                "comment": order_goods.comment,
                "score": order_goods.score
            }
            comment_list.append(order_goods_data)

        # 3, 返回响应
        res = {
            'code': RET.OK,
            'errmsg': '成功',
            'goods_comment_list':comment_list
        }
        return http.JsonResponse(res)
        pass